package com.app.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.model.*;
import com.app.server.*;
import com.app.utils.CommonHelp;
import com.app.utils.SMSUtils;
import com.app.utils.TokenUtils;
import com.app.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

/**
 * 报灾信息
 */
@Slf4j
@RestController
@RequestMapping("/sbbz/disaster")
public class DisasterReportingController {

    @Autowired
    private DisasterReportingService disasterReportingService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private UnitsDisasterService unitsDisasterService;
    @Autowired
    private DisasterHandleService handleService;
    @Autowired
    private RecordFileService recordFileService;
    @Resource
    private SMSUtils smsUtils;
    @Autowired
    private ClaimsSettlementService claimsSettlementService;

    // 查询列表
    @GetMapping("/getDisasterList")
    public Result getDisasterList(@RequestParam(defaultValue = "0") Integer page,
                                  @RequestParam(defaultValue = "10") Integer limit, Integer departmentId, Integer type, Integer claimsSettlementStatus, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminStringId = TokenUtils.verify(token);
        if (adminStringId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        Integer adminId = Integer.valueOf(adminStringId);
        AdminUserModel adminUser = adminUserService.getById(adminId);
        if (adminUser == null) {
            return Result.error(406, "用户不存在");
        }
        Integer roleId = adminUser.getRoleId();
        Integer unitsId = adminUser.getUnitsId();
        //如果是超级管理员查全部
        if (roleId == 1 || roleId == 3) {
            DisasterReportingVo disasterReportingVo = disasterReportingService.getDisasterList(page, limit, departmentId, type, claimsSettlementStatus);
            return Result.success(disasterReportingVo);
        }
        //根据当前登录的单位查询列表
        DisasterReportingVo disasterByUnitsList = disasterReportingService.getDisasterByUnitsList(page, limit, departmentId, type, unitsId, claimsSettlementStatus);

        return Result.success(disasterByUnitsList);
    }

    //根据id查询
    @GetMapping("/getDisasterById")
    public Result getDisasterById(Integer id) {
        //查询报灾管理信息
        DisasterReportingModel disasterReporting = disasterReportingService.getById(id);
        if (disasterReporting == null) {
            return Result.success("数据不存在");
        }
        String openId = disasterReporting.getOpenId();
        QueryWrapper<UserModel> qwUser = new QueryWrapper<>();
        qwUser.eq("open_id", openId);
        UserModel user = userService.getOne(qwUser);
        if (disasterReporting.getIsAnonymous() == 1) {
            disasterReporting.setUsername(DesensitizedUtil.chineseName(user.getName()));
            disasterReporting.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
        } else {
            disasterReporting.setUsername(user.getName());
            disasterReporting.setPhone(user.getPhone());
        }
        QueryWrapper<RecordFileModel> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.orderByDesc("id");
        if (disasterReporting.getFileId() != null) {
            String[] split = disasterReporting.getFileId().split(",");
            List<String> urlList = new ArrayList<>();
            List<String> videoUrlList = new ArrayList<>();
            for (String s : split) {
                RecordFileModel recordFileModel = recordFileService.getById(s);
                if (recordFileModel.getFileType() != null && recordFileModel.getFileType() == 1) {
                    urlList.add(recordFileModel.getUrl());
                } else if (recordFileModel.getFileType() != null && recordFileModel.getFileType() == 2) {
                    videoUrlList.add(recordFileModel.getUrl());
                }
            }
            disasterReporting.setPic(urlList.toArray(new String[0]));
            disasterReporting.setVideo(videoUrlList.toArray(new String[0]));
        }
        QueryWrapper<CategoryModel> qw = new QueryWrapper<>();
        qw.eq("id", disasterReporting.getType());
        CategoryModel category = categoryService.getOne(qw);
        disasterReporting.setTypeText(category.getName());

        //如果分配状态为3，那么详情中添加处理信息
        Integer allocationStatus = disasterReporting.getAllocationStatus();
        if (allocationStatus == 3) {
            //处理状态为3时 带处理对象
            disasterReporting = disasterReportingService.setDisasterHandle(disasterReporting);
        }
        QueryWrapper<ClaimsSettlementModel> claimsSettlementModelQueryWrapper = new QueryWrapper<>();
        claimsSettlementModelQueryWrapper.eq("report_id", disasterReporting.getId());
        try {
            ClaimsSettlementModel model = claimsSettlementService.getOne(claimsSettlementModelQueryWrapper);
            if (model != null) {
                disasterReporting.setClaimsSettlementModel(model);
                if (StrUtil.isNotBlank(model.getRelatedMaterials())) {
                    List<FileVo> list = JSON.parseObject(model.getRelatedMaterials(), new TypeReference<List<FileVo>>() {
                    });
                    model.setFileList(list);
                }
            }
        } catch (Exception e) {
            log.info(e.toString());
        }
        List<UnitsManagerModel> unitsManagerModels = unitsDisasterService.getByReportId(disasterReporting.getId());
        if (!unitsManagerModels.isEmpty()) {
            disasterReporting.setUnitsManagerModels(unitsManagerModels);
        }
        return Result.success(disasterReporting);
    }

    //分配报灾
    @GetMapping("/allocation")
    public Result updateAllocation(Integer id, @RequestParam("unitsId") Integer[] unitsIds) {
        DisasterReportingModel disasterReporting = new DisasterReportingModel();
        disasterReporting.setId(id);
        disasterReporting.setAllocationStatus(2);

        disasterReportingService.updateById(disasterReporting);
        for (Integer unitsId : unitsIds) {
            UnitsDisasterModel unitsDisaster = new UnitsDisasterModel();
            unitsDisaster.setDisasterId(id);
            unitsDisaster.setUnitsId(unitsId);
            unitsDisaster.setCreateTime(CommonHelp.getNowTimestamp());
            unitsDisasterService.save(unitsDisaster);
        }
        List<Integer> unitsIdsList = Arrays.asList(unitsIds);
        QueryWrapper<AdminUserModel> adminUserModelQueryWrapper = new QueryWrapper<>();
        adminUserModelQueryWrapper.in("units_id", unitsIdsList);
        List<AdminUserModel> userModelList = adminUserService.list(adminUserModelQueryWrapper);
        for (AdminUserModel adminUserModel : userModelList) {
            if (adminUserModel != null && adminUserModel.getPhone() != null) {
                if (PhoneUtil.isMobile(adminUserModel.getPhone())) {
                    synchronized (this.smsUtils) {
                        this.smsUtils.allocationSms(adminUserModel.getPhone(), adminUserModel.getRealName());
                    }
                }
            }
        }
        return Result.success("分发成功");
    }

    //获取灾害类型列表
    @GetMapping("/getDisasterType")
    public Result getDisasterType() {
        List<CategoryModel> disasterTypeList = categoryService.getDisasterType();
        return Result.success(disasterTypeList);
    }

    //根据报灾种类查询列表
    @GetMapping("/getDisasterByType")
    public Result getDisasterByType(Integer page, Integer limit, Integer type) {
        DisasterReportingVo disasterList = disasterReportingService.getDisasterByType(page, limit, type);
        return Result.success(disasterList);
    }

    //根据id删除
    @GetMapping("/delDisaster")
    public Result delDisaster(Integer id) {
        //删除报灾管理信息
        disasterReportingService.removeById(id);
        //先删除和他关联的报灾处理表数据
        QueryWrapper<DisasterHandleModel> qwHandle = new QueryWrapper<>();
        qwHandle.eq("disaster_id", id);
        handleService.remove(qwHandle);
        return Result.success("删除成功");
    }

    //获取灾害各类型统计饼图
    @GetMapping("/getDisasterTypeCount")
    public Result getDisasterTypeCount() {
        List<ValueAndNameVo> vos = new ArrayList<>();
        List<CategoryModel> categoryModelList = categoryService.selectByPid(1);
        for (int i = 0; i < categoryModelList.size(); i++) {
            ValueAndNameVo vo = new ValueAndNameVo();
            vo.setName(categoryModelList.get(i).getName());
            vo.setValue(disasterReportingService.selectCountByType(categoryModelList.get(i).getId()));
            vos.add(vo);
        }
//        List<ValueAndNameVo> disasterTypeCount = disasterReportingService.getDisasterTypeCount();
//        for (ValueAndNameVo valueAndNameVo : disasterTypeCount) {
//            CategoryModel categoryModel = categoryService.getById(valueAndNameVo.getName());
//            valueAndNameVo.setName(categoryModel.getName());
//        }
        return Result.success(vos);
    }

    //获取灾害各类型统计折线图
//    @GetMapping("/getDisasterMonthCount")
//    public Result getDisasterMonthCount() {
//        DisasterTypeVo disasterMonthCount = disasterReportingService.getDisasterMonthCount();
//        return Result.success(disasterMonthCount);
//    }

    @GetMapping("/getDisasterMonthCount")
    public Result getDisasterMonthCount() {
        DisasterTypeVo2 disasterMonthCount = disasterReportingService.getDisasterMonthCount2();
        return Result.success(disasterMonthCount);
    }

    // 用户查询报灾信息列表列表
    @GetMapping("/getUserDisasterList")
    public Result getUserDisasterList(Integer page, Integer limit, Integer type, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        DisasterReportingVo disasterReportingVo = disasterReportingService.getUserDisasterList(page, limit, type, openId);
        return Result.success(disasterReportingVo);
    }

    //用户新增和修改
    @PostMapping("/addAndUpdateDisaster")
    public Result addAndUpdateDisaster(@RequestBody DisasterReportingModel disasterReportingModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (StrUtil.isBlank(user.getAreaId())) {
            return Result.error(407, "请先完善个人信息");
        }
        DisasterReportingModel disasterReporting = disasterReportingService.getById(disasterReportingModel.getId());
        if (disasterReporting != null) {
            disasterReportingModel.setUpdateTime(CommonHelp.getNowTimestamp());
            disasterReportingService.updateById(disasterReportingModel);
            return Result.success("修改成功");
        } else {
            disasterReportingModel.setOpenId(user.getOpenId());
            disasterReportingModel.setCreateTime(CommonHelp.getNowTimestamp());
            StringBuilder s1 = new StringBuilder();
            if (disasterReportingModel.getPic() != null && disasterReportingModel.getPic().length > 0) {
                String[] pic = disasterReportingModel.getPic();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(1);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    s1.append(recordFileModel.getId()).append(",");
                }
            }
            if (disasterReportingModel.getVideo() != null && disasterReportingModel.getVideo().length > 0) {
                String[] pic = disasterReportingModel.getVideo();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(2);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    if (i == pic.length - 1) {
                        s1.append(recordFileModel.getId());
                    } else {
                        s1.append(recordFileModel.getId()).append(",");
                    }
                }
            }
            disasterReportingModel.setFileId(s1.toString());
            if (!disasterReportingModel.getArea().isEmpty()) {
                StringBuilder s2 = new StringBuilder();
                StringBuilder s3 = new StringBuilder();
                for (AreaModel areaModel : disasterReportingModel.getArea()) {
                    s2.append(areaModel.getValue()).append(",");
                    s3.append(areaModel.getText()).append("/");
                }
                disasterReportingModel.setAreaId(s2.substring(0, s2.toString().length() - 1));
                disasterReportingModel.setAreaName(s3.substring(0, s3.toString().length() - 1));
            }
            disasterReportingService.save(disasterReportingModel);
            CategoryModel category = categoryService.getById(disasterReportingModel.getType());
            disasterReportingModel.setTypeText(category.getName());
            QueryWrapper<AdminUserModel> adminUserModelQueryWrapper = new QueryWrapper<>();
            adminUserModelQueryWrapper.eq("role_id", 1);
            List<AdminUserModel> modelList = adminUserService.list(adminUserModelQueryWrapper);
            for (AdminUserModel adminUserModel : modelList) {
                if (adminUserModel != null && adminUserModel.getPhone() != null) {
                    if (PhoneUtil.isMobile(adminUserModel.getPhone())) {
                        synchronized (this.smsUtils) {
                            this.smsUtils.noticeSms(adminUserModel.getPhone(), disasterReportingModel.getTypeText(), disasterReportingModel.getPosition(), user.getPhone());
                        }
                    }
                }
            }
            return Result.success("添加成功");
        }
    }

    //白名单
    @GetMapping("/whiteList")
    public Result<Object> whiteList() {
        return Result.success(disasterReportingService.whiteList());
    }

    // 小程序查询所有列表
    @GetMapping("/getAllList")
    public Result getAllList(@RequestParam(defaultValue = "0") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit, Integer type, Integer claimsSettlementStatus, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        DisasterReportingVo disasterReportingVo = disasterReportingService.getDisasterList(page, limit, null, type, claimsSettlementStatus);
        return Result.success(disasterReportingVo);
    }
}
